import * as echarts from 'echarts'
import { useEffect, useRef } from 'react'
/*
饼图
const pieData = [{ year: '1991', value: 3 },{ year: '1995', value: 4.9 },{ year: '1999', value: 13 }]
<BarChart data={data} xField="year" yField="value" seriesField="type xAxisLabel={xAxisLabel} yAxisLabel={yAxisLabel} height={300}/>
*/
const PieChart = ({ data, xField, yField, seriesName, height = 400 }) => {
  const chartRef = useRef(null)
  useEffect(() => {
    // 初始化图表实例
    const chartInstance = echarts.init(chartRef.current)
    // 配置图表
    const option = {
      tooltip: {
        trigger: 'item' // 设置触发类型为基于数据项
      },
      series: [
        {
          name: seriesName,
          type: 'pie',
          radius: '55%',
          center: ['50%', '50%'],
          data: data.map(item => ({
            name: item[xField],
            value: item[yField]
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    // 渲染图表
    chartInstance.setOption(option)
    // 监听窗口大小变化事件，以重新调整图表尺寸
    window.addEventListener('resize', () => chartInstance.resize())
    // 清理函数
    return () => {
      chartInstance.dispose()
      window.removeEventListener('resize', () => chartInstance.resize())
    }
  }, [data, xField, yField, seriesName])
  return <div ref={chartRef} style={{ height }} />
}

export default PieChart
